import { ElMessage } from 'element-plus';
import request from './request'

function downloadFileBlob(opts: { url: any; prefix: string; method?: "POST" | undefined; data: any;}) {
    const { url, prefix, method = 'POST', data, } = opts
    return new Promise<void>(resolve => {
        request(url, {
            method,
            prefix,
            responseType: 'blob', 
            getResponse: true,
            ...(method === 'POST' ? { data } : { params: data })
        }).then((res) => {
            const contentDisposition = res.response.headers.get('Content-Disposition')
            if(contentDisposition) {
                const fileKey = contentDisposition.split(';')[1]
                // 文件名兼容处理
                let filename = decodeURIComponent(fileKey.split('filename=')[1]||fileKey.split('fileName=')[1])
                const filenameArr = filename.split('.')
                const fileType = filenameArr[filenameArr.length - 1]
                // 文件类型兼容处理，下载压缩包需添加type:"application/zip"类型
                const blob = new Blob([res.data], {...(fileType === 'rar'||fileType==='zip'? { type: "application/zip" } : {})});
                // IE兼容性处理
                const navigator = window?.navigator as any;
                if (navigator?.msSaveOrOpenBlob) {
                    navigator.msSaveOrOpenBlob(blob, filename);
                } else {
                    const url = window.URL.createObjectURL(blob);
                    const link:any = document.createElement('a');
                    link.href = url;
                    link.setAttribute('download', filename);
                    document.body.appendChild(link);
                    link.click();
                    link.parentNode.removeChild(link);
                    window.URL.revokeObjectURL(url); // 释放资源
                }
            } else {
                ElMessage.error('文件下载异常！');
            }
            resolve(res)
        });
    });
};

export default downloadFileBlob;